<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <title>demo by hans</title>
  <style>
    #canvas {
      border: 1px dashed #aaa;
    }
  </style>
</head>
<body>
  <canvas id="canvas" width="600" height="400"></canvas>
  <div class="ctrl">
    canMove<input type="checkbox" name="" id="canMove"><br>
    light<input type="checkbox" name="" id="light"><br>
    bounce<input type="checkbox" name="" checked id="bounce"><br>
  </div>
</body>
<script src="./js/ball.js"></script>
<script src="./js/scene.js"></script>
<script>
  let canvas = document.querySelector("#canvas");
  let ctx = canvas.getContext('2d');
  let WIDTH = canvas.width;
  let HEIGHT = canvas.height;
  setInterval(() => {
    if (!ball || emit) { return };
    ctx.clearRect(0, 0, WIDTH, HEIGHT);
    if (!ball.alive) {
      ball = null;
      return;
    }
    ball.canMove = canMove.checked;
    ball.light = light.checked; 
    ball.bounce = bounce.checked ? -0.7 : -1; 
    ball.update();
    ctx.fillStyle = '#222';
    ctx.font = "20px Georgia";
    ball.toString().split(';').forEach((e, i) => {
      ctx.fillText(e, 10, 20 * i + 20);
    })
    ctx.fillText(`Ball对象介绍，By hans`, WIDTH - 250, 30);
  }, 1000/60)
  
  let ball = null;
  let emit = false;
  let posX = 0;
  let posY = 0;
  let rate = 0.01;

  canvas.onmousedown = e => {
    posX = e.offsetX;
    posY = e.offsetY;
    emit = true;
  }
  canvas.onmouseup = e => {
    emit = false;
    let vx = (e.offsetX - posX) * rate;
    let vy = (e.offsetY - posY) * rate;
    ball = new Ball({ posX, posY, ctx, vx, vy });
    ball.birth = new Date();
    ball.init({ ctx, })
  }
  canvas.onmousemove = e => {
    if (emit) {
      ctx.fillStyle = '#eee';
      ctx.fillRect(0, 0, WIDTH, HEIGHT);
      ctx.strokeStyle = '#f60';
      ctx.beginPath();
      ctx.moveTo(posX, posY);
      ctx.lineTo(e.offsetX, e.offsetY);
      ctx.closePath();
      ctx.stroke();
    }
  }

</script>

